#!/usr/bin/env bash

wifiId="86500510002000300030000011bc56590804"

last_ts=`date +'%s'`
line_num=0
last_line=''
show_lines_num=20

cd /var/log/nb-iot-platform/ac-julink

echo "" >result.txt

cat ac-julink.WARNING | grep "$wifiId" | grep -Ei "RECORD:|EOF|reset|conn" > $wifiId.logs.txt

cat $wifiId.logs.txt | while read line
do
  line_num=$(($line_num + 1))
  if [[ $line =~ "RECORD:902" ]];then
    datetime902=`echo $line | awk '{print $2, $3}' | sed "s@\n@@g"`
    ts902=$(date +'%s' -d "$datetime902")
    if [ $(($ts902 - $last_ts)) -gt 80 ]; then
      echo "line_num: $line_num" >> result.txt
      from=$(($line_num - $show_lines_num))
      to=$(($line_num + $show_lines_num))

      cmd="${from},${to}p"
      echo "++++++++++++++++++++++++++" >> result.txt
      sed -n "$cmd" $wifiId.logs.txt >> result.txt
      echo "++++++++++++++++++++++++++" >> result.txt
    fi
    last_ts=$ts902
    last_line=$line
  fi
done
